package com.fuhe.chen.vendingmachine.controller.app;

import com.fuhe.chen.vendingmachine.dto.ApiResponse;
import com.fuhe.chen.vendingmachine.constant.MessageConstant;
import com.fuhe.chen.vendingmachine.constant.WebConst;
import com.fuhe.chen.vendingmachine.dto.UserDto;
import com.fuhe.chen.vendingmachine.pojo.User;
import com.fuhe.chen.vendingmachine.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@ResponseBody
@RequestMapping("/app/userInfo")
@Api(tags = "用户信息接口(面向app)")
public class UserInfoController {

    @Autowired
    IUserService userService;

    @ApiOperation(value = "根据用户名查询用户信息")
    @GetMapping({"/{username}"})
    public ApiResponse<UserDto> getUserInfo(@PathVariable String username, HttpServletRequest request){

        //只有本人可以查询自己的信息
        HttpSession session = request.getSession();
        User userInfo = (User) session.getAttribute(WebConst.LOGIN_SESSION_KEY);
        boolean isPermitted = userInfo.getName().equals(username);

        ApiResponse<UserDto> response = new ApiResponse<>();

        if(isPermitted){
            UserDto data = userService.findUserInfoById(username);
            response.setSuccess(true);
            response.setCode(MessageConstant.Success.SUCCESS_CODE);
            response.setMessage(MessageConstant.Success.QUERY_SUCCESS_MESSAGE);
            response.setData(data);
        }else {
            response.setSuccess(false);
            response.setCode(MessageConstant.Error.NO_QUERY_PERMISSION_CODE);
            response.setMessage(MessageConstant.Error.NO_QUERY_PERMISSION_MESSAGE);
        }

        return response;
    }
}
